import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:intl/intl.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:table_calendar/table_calendar.dart';
import '../constants/app_colors.dart';
import '../models/mood.dart';
import '../providers/mood_provider.dart';
import '../widgets/hand_drawn_emoji.dart';
import 'package:flutter/foundation.dart' show kIsWeb;
import 'dart:convert';

class DiaryScreen extends StatefulWidget {
  const DiaryScreen({Key? key}) : super(key: key);

  @override
  State<DiaryScreen> createState() => _DiaryScreenState();
}

class _DiaryScreenState extends State<DiaryScreen> {
  DateTime _focusedDay = DateTime.now();
  DateTime? _selectedDay;
  Map<DateTime, List<Mood>> _moodEvents = {};
  late final DateTime _firstDay;
  late final DateTime _lastDay;

  @override
  void initState() {
    super.initState();
    final now = DateTime.now();
    _firstDay = DateTime(now.year - 1, 1, 1);
    _lastDay = now;
    _selectedDay = _focusedDay;
    
    // 确保在构建完成后加载数据
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _initializeData();
    });
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _loadMoodRecords();
  }

  Future<void> _initializeData() async {
    try {
      final moodProvider = context.read<MoodProvider>();
      await moodProvider.init();
      await _loadMoodRecords();
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(
              '数据加载失败，请重试',
              style: GoogleFonts.zcoolKuaiLe(fontSize: 14),
            ),
            backgroundColor: Colors.red,
            duration: const Duration(seconds: 2),
            behavior: SnackBarBehavior.floating,
            margin: const EdgeInsets.all(16),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(10),
            ),
          ),
        );
      }
    }
  }

  Future<void> _loadMoodRecords() async {
    try {
      final moodProvider = context.read<MoodProvider>();
      final records = await moodProvider.getAllMoods();
      
      final events = <DateTime, List<Mood>>{};
      for (var mood in records) {
        final date = DateFormat('yyyy-MM-dd').parse(mood.date);
        if (events[date] == null) {
          events[date] = [];
        }
        events[date]!.add(mood);
      }
      
      // 对每一天的情绪记录按创建时间倒序排序，确保最新的记录在最前面
      events.forEach((date, moods) {
        moods.sort((a, b) => b.createdAt.compareTo(a.createdAt));
      });
      
      if (mounted) {
        setState(() {
          _moodEvents = events;
        });
      }
    } catch (e) {
      debugPrint('加载情绪记录失败: $e');
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(
              '加载记录失败，请重试',
              style: GoogleFonts.zcoolKuaiLe(fontSize: 14),
            ),
            backgroundColor: Colors.red,
            duration: const Duration(seconds: 2),
            behavior: SnackBarBehavior.floating,
            margin: const EdgeInsets.all(16),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(10),
            ),
          ),
        );
      }
    }
  }

  List<Mood> _getEventsForDay(DateTime day) {
    final normalizedDay = DateTime(day.year, day.month, day.day);
    return _moodEvents[normalizedDay] ?? [];
  }

  Widget _buildMoodImage(String imagePath, {bool isThumbnail = false}) {
    if (kIsWeb) {
      try {
        return Image.memory(
          base64Decode(imagePath),
          height: isThumbnail ? 100 : 200,
          width: isThumbnail ? 100 : double.infinity,
          fit: BoxFit.cover,
        );
      } catch (e) {
        debugPrint('Error loading web image: $e');
        return Container();
      }
    } else {
      return Image.file(
        File(imagePath),
        height: isThumbnail ? 100 : 200,
        width: isThumbnail ? 100 : double.infinity,
        fit: BoxFit.cover,
      );
    }
  }

  void _showImagePreview(BuildContext context, String imagePath) {
    showDialog(
      context: context,
      barrierColor: Colors.black,
      builder: (context) => GestureDetector(
        onTap: () => Navigator.pop(context),
        child: Center(
          child: kIsWeb
              ? Image.memory(base64Decode(imagePath))
              : Image.file(File(imagePath)),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[50],
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        centerTitle: true,
        title: Text(
          '情绪记录',
          style: GoogleFonts.zcoolKuaiLe(
            fontSize: 24,
            fontWeight: FontWeight.bold,
          ),
        ),
        actions: [
          IconButton(
            icon: Icon(Icons.refresh, color: AppColors.textPrimary),
            onPressed: _loadMoodRecords,
          ),
        ],
      ),
      body: ListView(
        children: [
          _buildCalendar(),
          if (_selectedDay != null) ...[
            if (_getEventsForDay(_selectedDay!).isEmpty)
              Padding(
                padding: const EdgeInsets.only(top: 32),
                child: Center(
                  child: Text(
                    '这一天还没有记录哦',
                    style: GoogleFonts.zcoolKuaiLe(
                      fontSize: 18,
                      color: AppColors.textSecondary,
                    ),
                  ),
                ),
              )
            else
              Padding(
                padding: const EdgeInsets.fromLTRB(16, 0, 16, 16),
                child: Column(
                  children: _getEventsForDay(_selectedDay!).map((mood) => _buildMoodCard(mood)).toList(),
                ),
              ),
          ],
        ],
      ),
    );
  }

  Widget _buildMoodCard(Mood mood) {
    return GestureDetector(
      onLongPress: () async {
        // 使用 HapticFeedback 提供触觉反馈
        await HapticFeedback.heavyImpact();
        
        if (!mounted) return;
        
        showDialog(
          context: context,
          builder: (context) => AlertDialog(
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(16),
            ),
            title: Text(
              '删除记录',
              style: GoogleFonts.zcoolKuaiLe(
                fontSize: 20,
                fontWeight: FontWeight.bold,
              ),
            ),
            content: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  '确定要删除这条记录吗？',
                  style: GoogleFonts.zcoolKuaiLe(
                    fontSize: 16,
                  ),
                ),
                const SizedBox(height: 8),
                Text(
                  '记录时间：${DateFormat('M月d日 HH:mm').format(mood.createdAt)}',
                  style: GoogleFonts.zcoolKuaiLe(
                    fontSize: 14,
                    color: AppColors.textSecondary,
                  ),
                ),
              ],
            ),
            actions: [
              TextButton(
                onPressed: () => Navigator.pop(context),
                child: Text(
                  '取消',
                  style: GoogleFonts.zcoolKuaiLe(
                    fontSize: 16,
                    color: Colors.grey,
                  ),
                ),
              ),
              TextButton(
                onPressed: () async {
                  Navigator.pop(context);
                  if (mood.id != null) {
                    final moodProvider = context.read<MoodProvider>();
                    final success = await moodProvider.deleteMood(mood.id!);
                    if (success && mounted) {
                      await _loadMoodRecords();
                      ScaffoldMessenger.of(context).showSnackBar(
                        SnackBar(
                          content: Text(
                            '记录已删除',
                            style: GoogleFonts.zcoolKuaiLe(fontSize: 14),
                          ),
                          backgroundColor: AppColors.success,
                        ),
                      );
                    }
                  }
                },
                child: Text(
                  '删除',
                  style: GoogleFonts.zcoolKuaiLe(
                    fontSize: 16,
                    color: Colors.red,
                  ),
                ),
              ),
            ],
          ),
        );
      },
      child: Container(
        margin: const EdgeInsets.only(bottom: 16),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(16),
          border: Border.all(color: Colors.grey.shade200),
        ),
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Text(
                    _getMoodDescription(mood.intensity, mood.emotions),
                    style: GoogleFonts.zcoolKuaiLe(
                      fontSize: 18,
                      fontWeight: FontWeight.w600,
                      color: AppColors.textPrimary,
                    ),
                  ),
                  const Spacer(),
                  Container(
                    padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
                    decoration: BoxDecoration(
                      color: _getMoodColor(mood.intensity).withOpacity(0.1),
                      borderRadius: BorderRadius.circular(12),
                    ),
                    child: Text(
                      '强度 ${mood.intensity}/10',
                      style: GoogleFonts.zcoolKuaiLe(
                        fontSize: 14,
                        color: _getMoodColor(mood.intensity),
                      ),
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 8),
              Text(
                DateFormat('M月d日 HH:mm').format(mood.createdAt),
                style: GoogleFonts.zcoolKuaiLe(
                  fontSize: 14,
                  color: AppColors.textSecondary,
                ),
              ),
              Builder(
                builder: (context) {
                  final hasValidTriggers = mood.triggers.isNotEmpty && mood.triggers.any((t) => t.trim().isNotEmpty);
                  final hasValidReactions = mood.bodyReactions.isNotEmpty && mood.bodyReactions.any((r) => r.trim().isNotEmpty);
                  
                  if (!hasValidTriggers && !hasValidReactions) {
                    return const SizedBox.shrink();
                  }
                  
                  return Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      const SizedBox(height: 8),
                      Wrap(
                        spacing: 8,
                        runSpacing: 8,
                        children: [
                          if (hasValidTriggers)
                            ...mood.triggers
                                .where((t) => t.trim().isNotEmpty)
                                .map((trigger) => Container(
                                  padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                                  decoration: BoxDecoration(
                                    color: Colors.blue.withOpacity(0.1),
                                    borderRadius: BorderRadius.circular(20),
                                  ),
                                  child: Text(
                                    trigger,
                                    style: GoogleFonts.zcoolKuaiLe(
                                      fontSize: 14,
                                      color: Colors.blue,
                                    ),
                                  ),
                                )),
                          if (hasValidReactions)
                            ...mood.bodyReactions
                                .where((r) => r.trim().isNotEmpty)
                                .map((reaction) => Container(
                                  padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                                  decoration: BoxDecoration(
                                    color: Colors.purple.withOpacity(0.1),
                                    borderRadius: BorderRadius.circular(20),
                                  ),
                                  child: Text(
                                    reaction,
                                    style: GoogleFonts.zcoolKuaiLe(
                                      fontSize: 14,
                                      color: Colors.purple,
                                    ),
                                  ),
                                )),
                        ],
                      ),
                    ],
                  );
                },
              ),
              if (mood.description.isNotEmpty) ...[
                const SizedBox(height: 12),
                Text(
                  mood.description,
                  style: GoogleFonts.zcoolKuaiLe(
                    fontSize: 16,
                    color: AppColors.textPrimary,
                  ),
                ),
              ],
              if (mood.imagePath != null) ...[
                const SizedBox(height: 8),
                GestureDetector(
                  onTap: () => _showImagePreview(context, mood.imagePath!),
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(8),
                    child: _buildMoodImage(mood.imagePath!, isThumbnail: true),
                  ),
                ),
              ],
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildCalendar() {
    return IgnorePointer(
      ignoring: false,
      child: Container(
        margin: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(16),
          border: Border.all(color: Colors.grey.shade200),
        ),
        child: TableCalendar<Mood>(
          firstDay: _firstDay,
          lastDay: _lastDay,
          focusedDay: _focusedDay,
          calendarFormat: CalendarFormat.month,
          availableCalendarFormats: const {
            CalendarFormat.month: '月'
          },
          selectedDayPredicate: (day) => isSameDay(_selectedDay, day),
          eventLoader: _getEventsForDay,
          calendarStyle: CalendarStyle(
            markersMaxCount: 1,
            markerSize: 8,
            markerMargin: const EdgeInsets.only(top: 4),
            markersAnchor: 1.5,
            markerDecoration: BoxDecoration(
              color: AppColors.primary,
              shape: BoxShape.circle,
              border: Border.all(
                color: Colors.white,
                width: 1.5,
              ),
            ),
            selectedDecoration: BoxDecoration(
              color: AppColors.primary.withOpacity(0.7),
              shape: BoxShape.circle,
            ),
            todayDecoration: BoxDecoration(
              color: AppColors.primary.withOpacity(0.3),
              shape: BoxShape.circle,
            ),
            selectedTextStyle: const TextStyle(
              color: Colors.white,
              fontWeight: FontWeight.bold,
            ),
            outsideDaysVisible: false,
            weekendTextStyle: const TextStyle(color: Colors.black87),
            holidayTextStyle: const TextStyle(color: Colors.black87),
            cellMargin: const EdgeInsets.all(2),
            cellPadding: EdgeInsets.zero,
            tablePadding: const EdgeInsets.symmetric(horizontal: 12),
          ),
          headerStyle: HeaderStyle(
            titleTextStyle: GoogleFonts.zcoolKuaiLe(
              fontSize: 20,
              fontWeight: FontWeight.bold,
              color: AppColors.textPrimary,
            ),
            formatButtonVisible: false,
            leftChevronIcon: Icon(Icons.chevron_left, color: AppColors.textPrimary),
            rightChevronIcon: Icon(Icons.chevron_right, color: AppColors.textPrimary),
            headerPadding: const EdgeInsets.symmetric(vertical: 8),
            headerMargin: const EdgeInsets.only(bottom: 4),
            titleCentered: true,
          ),
          calendarBuilders: CalendarBuilders(
            headerTitleBuilder: (context, day) {
              return GestureDetector(
                onTap: () => _showYearMonthPicker(context, day),
                child: Container(
                  padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text(
                        '${day.year}年${day.month}月',
                        style: GoogleFonts.zcoolKuaiLe(
                          fontSize: 20,
                          fontWeight: FontWeight.bold,
                          color: AppColors.textPrimary,
                        ),
                      ),
                      const SizedBox(width: 4),
                      Icon(
                        Icons.arrow_drop_down,
                        color: AppColors.textPrimary,
                        size: 24,
                      ),
                    ],
                  ),
                ),
              );
            },
          ),
          daysOfWeekStyle: DaysOfWeekStyle(
            weekdayStyle: GoogleFonts.zcoolKuaiLe(
              fontSize: 14,
              color: AppColors.textPrimary,
            ),
            weekendStyle: GoogleFonts.zcoolKuaiLe(
              fontSize: 14,
              color: AppColors.textPrimary,
            ),
            dowTextFormatter: (date, locale) {
              const weekdayMap = {
                1: '一',
                2: '二',
                3: '三',
                4: '四',
                5: '五',
                6: '六',
                7: '日',
              };
              return weekdayMap[date.weekday] ?? '';
            },
          ),
          rowHeight: 40,
          daysOfWeekHeight: 32,
          onDaySelected: (selectedDay, focusedDay) {
            setState(() {
              _selectedDay = selectedDay;
              _focusedDay = focusedDay;
            });
          },
          onPageChanged: (focusedDay) {
            setState(() {
              _focusedDay = focusedDay;
            });
          },
        ),
      ),
    );
  }

  void _showYearMonthPicker(BuildContext context, DateTime initialDate) {
    final now = DateTime.now();
    final minYear = now.year - 10;
    final maxYear = now.year;
    
    // 创建一个 ScrollController
    final scrollController = ScrollController(
      initialScrollOffset: (now.year - minYear) * 56.0, // 56.0 是每个年份项的高度
    );
    
    showDialog(
      context: context,
      barrierDismissible: true,
      builder: (context) => AlertDialog(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(16),
        ),
        title: Text(
          '选择年月',
          style: GoogleFonts.zcoolKuaiLe(
            fontSize: 20,
            fontWeight: FontWeight.bold,
          ),
          textAlign: TextAlign.center,
        ),
        content: SizedBox(
          width: double.maxFinite,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Container(
                height: 200,
                padding: const EdgeInsets.symmetric(horizontal: 16),
                child: ListView.builder(
                  controller: scrollController,
                  itemCount: maxYear - minYear + 1,
                  itemBuilder: (context, index) {
                    final year = minYear + index;
                    final isSelected = year == _focusedDay.year;
                    return InkWell(
                      onTap: () {
                        final newDate = DateTime(
                          year,
                          _focusedDay.month,
                          1,
                        );
                        
                        if (newDate.isBefore(_firstDay)) {
                          setState(() {
                            _focusedDay = _firstDay;
                          });
                        } else if (newDate.isAfter(_lastDay)) {
                          setState(() {
                            _focusedDay = DateTime(_lastDay.year, _lastDay.month, 1);
                          });
                        } else {
                          setState(() {
                            _focusedDay = newDate;
                          });
                        }
                        
                        Navigator.pop(context);
                        _showMonthPicker(context);
                      },
                      child: Container(
                        height: 56,
                        padding: const EdgeInsets.symmetric(horizontal: 16),
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                          color: isSelected ? AppColors.primary.withOpacity(0.1) : Colors.transparent,
                          borderRadius: BorderRadius.circular(8),
                        ),
                        child: Text(
                          '$year年',
                          style: GoogleFonts.zcoolKuaiLe(
                            fontSize: 18,
                            color: isSelected ? AppColors.primary : AppColors.textPrimary,
                            fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
                          ),
                        ),
                      ),
                    );
                  },
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  void _showMonthPicker(BuildContext context) {
    final now = DateTime.now();
    final isCurrentYear = _focusedDay.year == now.year;
    
    showDialog(
      context: context,
      barrierDismissible: true,
      builder: (context) => AlertDialog(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(16),
        ),
        title: Text(
          '选择月份',
          style: GoogleFonts.zcoolKuaiLe(
            fontSize: 20,
            fontWeight: FontWeight.bold,
          ),
          textAlign: TextAlign.center,
        ),
        content: Container(
          width: double.maxFinite,
          child: Wrap(
            alignment: WrapAlignment.center,
            spacing: 12,
            runSpacing: 12,
            children: List.generate(12, (index) {
              final month = index + 1;
              final isSelected = month == _focusedDay.month;
              final isDisabled = isCurrentYear && month > now.month;
              
              return InkWell(
                onTap: isDisabled ? null : () {
                  final newDate = DateTime(_focusedDay.year, month, 1);
                  setState(() {
                    _focusedDay = newDate;
                    _selectedDay = newDate;
                  });
                  Navigator.pop(context);
                },
                borderRadius: BorderRadius.circular(20),
                child: Container(
                  width: 60,
                  height: 40,
                  decoration: BoxDecoration(
                    color: isDisabled 
                      ? Colors.grey[200]
                      : isSelected 
                        ? AppColors.primary 
                        : Colors.grey[100],
                    borderRadius: BorderRadius.circular(20),
                  ),
                  child: Center(
                    child: Text(
                      '$month月',
                      style: GoogleFonts.zcoolKuaiLe(
                        fontSize: 16,
                        color: isDisabled 
                          ? Colors.grey[400]
                          : isSelected 
                            ? Colors.white 
                            : AppColors.textPrimary,
                        fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
                      ),
                    ),
                  ),
                ),
              );
            }),
          ),
        ),
      ),
    );
  }

  String _getMoodDescription(int intensity, [List<String>? emotions]) {
    String baseName;
    if (intensity >= 8) {
      baseName = '开心';
    } else if (intensity >= 6) {
      baseName = '愉快';
    } else if (intensity >= 4) {
      baseName = '平静';
    } else if (intensity >= 2) {
      baseName = '低落';
    } else {
      baseName = '难过';
    }

    // 如果有具体的情绪词，添加到基础名称后
    if (emotions != null && emotions.isNotEmpty) {
      return '$baseName，${emotions.join("，")}';
    }
    
    return baseName;
  }

  Color _getMoodColor(int intensity) {
    if (intensity >= 8) {
      return Colors.green;
    } else if (intensity >= 6) {
      return Colors.lightGreen;
    } else if (intensity >= 4) {
      return Colors.orange;
    } else if (intensity >= 2) {
      return Colors.deepOrange;
    } else {
      return Colors.red;
    }
  }
} 